import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-11-30
 * Time: 23:18
 */
public class Solution {
    public int[][] merge(int[][] intervals) {
        if(intervals.length==0){
            return new int[1][2];
        }
        //先按照start排序
        Arrays.sort(intervals,(a, b)->a[0]-b[0]);
        List<int[]> merged=new ArrayList<>();
        for(int i=0;i<intervals.length;i++){
            //list中没有元素或者没有发生重叠就直接添加进去
            if(merged.size()==0||merged.get(merged.size()-1)[1]<intervals[i][0]){
                merged.add(new int[]{intervals[i][0],intervals[i][1]});
            }else{
                //有重叠,start不用变,end取较大值
                merged.get(merged.size()-1)[1]=Math.max(merged.get(merged.size()-1)[1],intervals[i][1]);
            }
        }
        return merged.toArray(new int[merged.size()][2]);
    }
}